from flask import json, request
from werkzeug.exceptions import HTTPException


class APIException(HTTPException):
    code = 500  # HTTP状态码
    msg = "sorry, we made a mistake (*￣︶￣)!"
    error_code = 999

    def __init__(self, msg=None, code=None, error_code=None):
        if code:
            self.code = code
        if msg:
            self.msg = msg
        if error_code:
            self.error_code = error_code

        super(APIException, self).__init__(msg, None)

    def get_body(self, environ=None):
        # {“msg”:"xxx", "error_code":1000,"request":url}
        body = dict(
            msg=self.msg,
            error_code=self.error_code,
            request=f'{request.method} {self.get_url_no_param()}'
        )
        text = json.dumps(body)
        return text

    @staticmethod
    def get_url_no_param():
        full_path = request.full_path
        return full_path.split('?')[0]

    def get_headers(self, environ=None):
        return [("Content-Type", "application/json")]
